package com.derbysoft.defender.util;

import org.springframework.util.Assert;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class WebUtil {
    private WebUtil() {
    }

    public static void response(HttpServletResponse response, Object data) {
        Assert.notNull(response, "response should not be null");
        if (data == null) {
            return;
        }

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;

        try {
            String s = (data instanceof String) ? (String) data : JsonUtil.toJson(data);
            writer = response.getWriter();
            writer.write(s);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
